package com.parking.order.util;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.parking.order.model.param.AlipayParam;
import com.parking.order.model.param.AlipayRefundParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 支付工具类
 * */
@Component
public class AlipayUtil {
    /**
     * 支付宝接口调用代理
     * */
    @Autowired
    private AlipayClient alipayClient;

    /**
     * 支付
     * 参数: orderId   订单编号
     *      price     订单价格
     *      subject   订单主题
     *      body      订单内容
     *      returnUrl 前端返回Url
     *      notifyUrl 后端回调Url
     * 返回: 支付结果 包括支付申请是否成功 以及支付页面的HTML
     * */
    public String pay(AlipayParam param) throws Exception {
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        String content = "{\"out_trade_no\":\"" + param.getOrderId() + "\"," + "\"total_amount\":\"" + param.getMoney()
                + "\"," + "\"subject\":\"" + param.getSubject() + "\"," + "\"body\":\"" + param.getBody() + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}";
        request.setBizContent(content);
        request.setReturnUrl(param.getReturnUrl());
        request.setNotifyUrl(param.getNotifyUrl());
        AlipayTradePagePayResponse response = alipayClient.pageExecute(request);
        if(response.isSuccess()) {
            return response.getBody();
        }
        throw new Exception("发起支付失败");
    }

    /**
     * 查询支付状态
     * 参数: orderId 订单编号
     * 返回: 支付状态查询结果的JSON字符串
     * */
    public String selectOrderPayState(String orderId) throws AlipayApiException {
        AlipayTradeQueryRequest alipayRequest = new AlipayTradeQueryRequest();
        alipayRequest.setBizContent("{\"out_trade_no\":\"" + orderId + "\"}");
        AlipayTradeQueryResponse execute = alipayClient.execute(alipayRequest);
        return execute.getBody();
    }

    /**
     * 申请退款
     * 参数: orderId 订单编号
     *       refundAmount 退单金额
     *       refundReason 退单理由
     * */
    public void refund(AlipayRefundParam param) throws Exception{
        AlipayTradeQueryRequest alipayRequest = new AlipayTradeQueryRequest();
        alipayRequest.setBizContent("{\"out_trade_no\":\""+ param.getOrderId()+"\"}" +
                "{\"refund_amount\":\""+ param.getRefundAmount()+"\"}" +
                "{\"refund_reason\":\""+ param.getRefundReason()+"\"}");
        alipayClient.execute(alipayRequest);
    }
}
